package com.example.geguo.nettyclientchatdemo;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.util.concurrent.atomic.AtomicInteger;
/**
 * 这么多状态我已经搞不清了
 *
 * */
public class LongConnService extends Service {
	public static String ACTION = "com.example.geguo.nettyclientchatdemo.LongConnService";
	private static NettyConnectionManager minaLongConnectManager;
	private Context context;

	private static final String TAG ="LongConnService";

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "onCreate: ");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		context = getApplicationContext();
		ObserverManager.addObserver("stopConn", new ObserverListener() {
			@Override
			public void observer(String from, Object obj) {
				closeConnect();
			}
		});
		startLongConnect();
		return START_STICKY;// 被杀死后 会重启的呢
	}


	/**
	 * 关闭了服务又能怎样还是会重启啊
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();
		closeConnect();
	}

	/**
	 * 开始执行启动长连接的操作
	 */
	private void startLongConnect() {
		if (true) {// 判断网络
			if (minaLongConnectManager != null && minaLongConnectManager.checkConnectStatus()) {
				Log.i(TAG, "startLongConnect: 长连接状态正常...");
				return;
			}else{
				startThreadCreateConnect();
			}
		}

	}

	private final AtomicInteger mCount = new AtomicInteger(1);

	private void startThreadCreateConnect() {
//		if (UserConfig.getUserInfo().getB3Key() != null && UserConfig.getUserInfo().getSessionKey() != null) {
			System.gc();
//          这里重新开一个 需要把旧的干掉;防止跑两个
			new Thread(new Runnable() {
				@Override
				public void run() {
					// 执行具体启动长连接操作
					minaLongConnectManager = NettyConnectionManager.getInstance(context);
					minaLongConnectManager.startConnect();
				}
			}, "longConnectThread" + mCount.getAndIncrement()).start();
//		}
	}


	/**
	 * 如何通过控制 ConnectManager 来关闭服务呢？
	 * 妈的关闭了也没有用啊，还是会重启连接啊
	 */
	private void closeConnect() {
		if (minaLongConnectManager != null) {
			minaLongConnectManager.closeConnect();
		}
		minaLongConnectManager = null;
		// 停止长连接服务LongConnService
		stopSelf();
	}

	@Override
	public IBinder onBind(Intent intent) {
		throw new UnsupportedOperationException("Not yet implemented");
	}


}
